<template>
  <el-form
    :model="localFormData"
    label-width="auto"
    style="max-width: 650px"
    ref="ruleFormRef"
    :rules="rules"
    class=""
  >
    <el-row>
      <el-col :span="24">
        <h6 class="pb-3.5 text-gray-400 text-3.5">基础信息</h6>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="文件名称" prop="name" required>
          <el-input v-model="localFormData.file_name" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="文件上传" prop="thumbnail">
          <ThumbnailUpload
            :api="uploadFile"
            :allowedExtensions="['.jpg', '.jpeg', '.png', '.gif']"
            :maxSizeMB="0.3"
            :multiple="false"
            :limit="1"
            @success="handleSuccess"
            @error="handleError"
          ></ThumbnailUpload>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-form-item label="文件路径" prop="file_path">
          <el-input v-model="localFormData.file_path" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, defineExpose, watchEffect } from "vue";
import * as Api from "@/api/index";
import { FormFactory } from "@/core/forms/form-factory";
import { FileFormData } from "@/core/forms/file-form";
import type { FileItem } from "@/api/types/file";
import ThumbnailUpload from "@/components/upload/ThumbnailUpload.vue";
import { isCompleteURL } from "@/utils/util";

const SERVER_URL = import.meta.env.VITE_API_SERVER_URL;
const emit = defineEmits(["success"]);
const props = defineProps<{
  formData: FileItem;
  mode: "create" | "edit";
}>();


// 如果是编辑模式，初始化表单数据
const statusOptions = [
  { label: "正常", value: "normal" },
  { label: "已删除", value: "archived" },
];
const localFormData = ref(FormFactory.create("product") as FileFormData); // 如果是编辑模式，初始化表单数据
console.log(localFormData);

const ruleFormRef = ref();
const rules= { 
};
// 暴露给父组件的异步提交方法
const submit = async () => {
  if (!ruleFormRef.value) return;

  return ruleFormRef.value
    .validate()
    .then(async (valid: boolean) => {
      if (!valid) return false;

      const submitFormData = {
        ...localFormData.value.toSubmitData()                
      };

      try {
        console.log("提交表单数据:", submitFormData);
        // return;
        const response =
          props.mode === "create"
            ? await Api.createFile(submitFormData)
            : await Api.updateFile(props.formData.id, submitFormData);
        return true;
      } catch (err) {
        throw err; // 会被外部的catch捕获
      }
    })
    .catch((err: any) => {
      console.error("错误:", err);
      return false;
    });
};

const handleSuccess = (url: string) => {
  console.log("上传成功:", url);
  if (!isCompleteURL(url)) {
  } else {
  }
  console.log(localFormData.value);
};
const handleError = (err: any) => {
  console.error("上传失败:", err);
};
const handleSkuImageSuccess = (res: any, sku: any) => {
  sku.image = isCompleteURL(res.url) ? res.url : SERVER_URL + res.url;
};

const uploadFile=async (file: File) => { 
  try {
    // 这里实现你的上传逻辑，通常使用axios或fetch
    // 返回上传后的文件URL
    const formData = new FormData();
    formData.append("file", file);

    const response = await Api.upload("/upload/file", formData, "", {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    console.log(response);
    return response.url; // 假设后端返回包含url字段
  } catch (error) {
    console.log(error);
  }
};
// 自动响应props变化的智能初始化
watchEffect(() => {
  if (props.mode === "edit" && props.formData) {
    console.log("编辑模式，初始化表单数据", props.formData);
    localFormData.value = FormFactory.createFromExisting(
      "product",
      props.formData
    ) as FileFormData;
  } else {
    localFormData.value = FormFactory.create("file") as FileFormData;
  }
});
defineExpose({ submit });
onMounted(() => {
});
</script>
<style scoped lang="scss">
.avatar-uploader .avatar[data-v-11e0307c] {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* 暗黑模式下的悬停颜色 */
.dark :deep(.el-table__body tr:hover > td) {
  background-color: rgba(255, 255, 255, 0.08) !important;
}
</style>
